<template>
  <div class="app-container documentation-container">
    <div class="graph_wrapper" id="graph_wrapper">
      <div :class="{ example: true }" id="example">
        <div :class="{ graph_title: true, long: detail.provinceName && detail.provinceName.length > 6 }">
          {{ projectName }}
          <span style="float: right" @click="hideMax">关闭</span>
        </div>
        <div v-loading="loading" id="myMap" class="exampleMap"> </div>
      </div>

    </div>
  </div>
</template>

<script>
// import Graph from './graph.vue'
import loadBMap from '@/utils/loadBMap'
import { myProjectDetail, movePoint, customerProjectDetail } from '@/api/myProject'
const ak = "k5LYzWjOinI5GOcHpBgdxieo5ZVPGtLj"

export default {
  name: 'Documentation',
  // components: { Graph },
  data() {
    return {
      isAdmin: this.$store.state.user.roles.includes('admin'),
      projectId: null,
      loading: false,
      projectName: this.$route.params.name,
      detail:  { projectName: '北京'},
      mapObj: {},
      projects: sessionStorage.getItem("projectsAdmin")? JSON.parse(sessionStorage.getItem("projectsAdmin")) : {},
      mapObj: { projectId: 'a', city: '江西省', points: ['115.832058,28.714894', '116.421922,29.247737', '115.75502,27.76481', '115.019128,29.03372']},
      mapExample: null,
      blueIcon: null,
      greenIcon: null,
      yellowIcon: null,
      redIcon: null,
      dredIcon: null,
      pColors:{
        0: this.greenIcon,
        1: this.blueIcon,
        2: this.yellowIcon, // 黄色
        3: this.redIcon,
        4: this.dredIcon
      }

    }
  },
  computed: {
  },
  mounted() {
    // 百度地图版本
    this.initSize()


  },
  methods: {
    hideMax(){
      this.$router.push('/myProject/graph')
    },
    showMaxGraph(){
      this.loading = true
      let pArray = []
      this.detail.points.map((p,i) => {
        if(p.longitude && p.latitude){
          let lng = parseFloat(p.longitude), lat = parseFloat(p.latitude)
           let _point = new BMapGL.Point(lng, lat)

          let bdPoint
          new BMapGL.Convertor().translate([_point], 3, 5, (data) => {
            //  console.log(_point, data.points, '转换图标')
             bdPoint = data.points[0]
            //  pArray.push(bdPoint)
             pArray[i] = bdPoint
            // let marker = new BMapGL.Marker(_point, {
            let marker = new BMapGL.Marker(bdPoint, {
                icon: this.pColors[p.dataStatus],
                enableDragging: this.$store.state.user.accountType == 0
            });
            // 将标注添加到地图
            this.mapExample.addOverlay(marker);
            // let dragEndPoint = _point
            let dragEndPoint = bdPoint
            marker.addEventListener("dragend", () =>{
                let curPoint = marker.getPosition();
                dragEndPoint = curPoint
                //  console.log('拖拽位置', curPoint)
                new BMapGL.Convertor().translate([curPoint], 5, 3, (data) => {
                  movePoint({
                    deviceId: p.id,
                    longitude: data.points[0].lng,
                    latitude: data.points[0].lat
                  }).then(res => {
                    if(res.statusCode == '200') {
                      this.$message.success('重新定位成功！')
                    }
                  }).catch()
                })

            }, { passive: false});
            marker.addEventListener("click", () => {
              let curPoint = marker.getPosition();
                //  console.log('点击事件位置', curPoint)
                new BMapGL.Convertor().translate([curPoint], 5, 3, (data) => {
                  let opts = {
                      width: 280,
                      height: 160,
                      title:  `设备名称：${p.deviceName} `
                  };
                  let info = `
                  IMEI： ${p.imei} <br>
                  自定义编码： ${p.deviceCode} <br>
                  电子标签： ${p.rfid} <br>
                  经度： ${data.points[0].lng} <br>
                  纬度： ${data.points[0].lat} <br>
                  安装时间：${p.insTime} <br>`
                  let infoWindow = new BMapGL.InfoWindow( info, opts);
                  this.mapExample.openInfoWindow(infoWindow, dragEndPoint); // 开启信息窗口

                })
            },  { passive: false});
          });
        }

      })
      setTimeout(() => {
        this.loading = false
        let area = this.detail.countyName || this.detail.cityName || this.detail.provinceName
        // console.log(pArray, '调整视野', this.$route.query.long , this.$route.query.lat )
        if(pArray.length > 0){
          if(Number(this.$route.query.long) && Number(this.$route.query.lat)){
            new BMapGL.Convertor().translate([new BMapGL.Point(Number(this.$route.query.long),Number(this.$route.query.lat))], 3, 5, (data) => {
              this.mapExample.centerAndZoom(data.points[0], 18) // 初始化地图，设置中心点坐标和地图级别
            })
            // this.mapExample.centerAndZoom( new BMapGL.Point(Number(this.$route.query.long),Number(this.$route.query.lat)), 20)
          } else {
            this.mapExample.setViewport(pArray) // 调整视野
            this.drawBoundary(area, this.mapExample)

          }
        } else {
          this.drawBoundary(area, this.mapExample)

        }
      }, 500)


    },
    drawBoundary(city, map){
       // 设置区域覆盖物
        var bd = new BMapGL.Boundary()
        bd.get(city, (rs) => { // 获取行政区域
          // map.clearOverlays() // 清除地图覆盖物

          var count = rs.boundaries.length // 行政区域的点有多少个
          // 包含所有区域的点数组
          let pointArray = []

          // 为目标省会绘图（添加覆盖物）
          for (var i = 0; i < count; i++) {
            let ply = new BMapGL.Polygon(rs.boundaries[i],
              { strokeWeight: 5,
               strokeOpacity:1, //设置多边形边线透明度0-1
                StrokeStyle: "solid", //设置多边形边线样式为实线或虚线，取值 solid 或 dashedstrokeColor:"#ff0000", //设置多边形边线颜色
              // strokeColor: "#FF0000",
                strokeColor: '#003088',
                fillOpacity: 0.01,  //设置多边形填充颜色透明度0-1
                fillColor: ' #FFFFFF' } // //设置多边形填充颜色
            )
            let path = ply.getPath()
            pointArray = pointArray.concat(path)

            // map.addOverlay(ply) // 添加覆盖物
          }
          map.setViewport(pointArray) // 调整视野
        })
    },
    initSize(){
      let width = document.body.clientWidth - 200 * 1
      let height = document.body.clientHeight - 130
      document.getElementById('graph_wrapper').style.width = width + 'px'
      document.getElementById('graph_wrapper').style.height = height + 'px'

      loadBMap(ak).then(res => {

        this.greenIcon = new BMapGL.Icon("/imgs/marker1.png", new BMapGL.Size(25, 30));
        this.blueIcon = new BMapGL.Icon("/imgs/marker2.png", new BMapGL.Size(25, 30));
        this.yellowIcon = new BMapGL.Icon("/imgs/marker3.png", new BMapGL.Size(25, 30));
        this.redIcon = new BMapGL.Icon("/imgs/marker4.png", new BMapGL.Size(25, 30));
        this.dredIcon = new BMapGL.Icon("/imgs/marker5.png", new BMapGL.Size(25, 30));
        this.pColors ={
          0: this.greenIcon,
          1: this.blueIcon,
          2: this.yellowIcon, // 黄色
          3: this.redIcon,
          4: this.dredIcon
        }

        this.mapExample = new BMapGL.Map('myMap') // 创建地图实例
        // this.mapExample.centerAndZoom('郑州市', 7) // 初始化地图，设置中心点坐标和地图级别
        this.mapExample.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
        this.mapExample.addControl(new BMapGL.ScaleControl()) // 添加比例尺控件
        this.mapExample.addControl(new BMapGL.ZoomControl())
        let projectDetail = {...this.projects}

      this.$nextTick( () => {
          if(this.isAdmin){
            myProjectDetail(this.projectId).then(res => {
              this.detail = {
                ...projectDetail,
                points: res.data,
              }
              this.showMaxGraph()
            }).catch()
          } else {
            customerProjectDetail({projectId: this.projectId }).then(res => {
              this.detail = {
                ...projectDetail,
                points: res.data,
              }
              this.showMaxGraph()
            }).catch()
          }
      })

      }).catch()
    }
  },
  created(){
    this.projectId = this.$route.params.id

  },
  destroyed(){
  /**
  * 销毁百度地图
    */
    try {
      // 注销地图（换成你初始化时定义的地图变量）
      this.mapExample = null;

      // 获取interval的最高ID然后遍历清除
      const HIGHEST_INTERVAL_ID = setInterval(';');
      for ( let i = 0 ; i < HIGHEST_INTERVAL_ID ; i++ ) {
        clearInterval(i);
      }

      // 获取百度地图创建的DOM并销毁
      const BAIDU_MAPS = document.querySelectorAll('.tangram-suggestion-main');
      BAIDU_MAPS.forEach( item => {
        document.body.removeChild(item);
      });

    } catch (e) {
      // console.log(e);
    }
  }
}
</script>

<style lang="scss" >
.hide {
  visibility: hidden;
}
.graph_wrapper {
  // margin: 0px auto;
  position: relative;
}
.example {

  width: 100%;
  height: calc( 100% - 60px);
  background: #0B1120;
  padding: 30px 50px;
  background: #0B1120 url('../../assets/imgs/map_bg.png') no-repeat;
  background-size: 100% 100%;
  .graph_title {
    color: #fff;
    font-size: 14px;
    background: url('../../assets/imgs/map_title_small.png') no-repeat;
    // background-size: 100% 100%;
    padding: 5px 20px;
    margin-bottom: 20px;
    &.long {
      background: url('../../assets/imgs/map_title_long.png') no-repeat;
    }
  }
  .exampleMap {
    width: 100%;
    height: calc( 100% - 100px);
    // height: 100%;
    touch-action:none
  }
}



.documentation-container {
  // margin: 0 20px;
  // padding: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  position: relative;

  .document-btn {
    flex-shrink: 0;
    display: block;
    cursor: pointer;
    background: black;
    color: white;
    height: 60px;
    padding: 0 16px;
    margin: 16px;
    line-height: 60px;
    font-size: 20px;
    text-align: center;
  }
}
</style>
